/**
 * @author liubaohui
 * @desc 前端搜索
 * @param {array} listData 响应数据列表
 * @param {object} searchParams  当前查询参数对象
 * @param {array} searchList  搜索组件搜索项
 * @returns {*}
 */
export default function frontSearch(listData, searchParams, searchList) {
  return listData.filter((item) => filterBySearch(item, searchParams, searchList))
}

/**
 * @author liubaohui
 * @desc 筛选方法
 * @param {object} item 数据项
 * @param {object} searchParams  当前查询参数对象
 * @param {array} searchList  搜索组件搜索项
 * @returns {boolean}
 */
function filterBySearch(item, searchParams, searchList) {
  let searchKeys = Object.keys(searchParams) // 搜索字段
  return searchKeys.every((key) => {
    let itemVal, // 列表项的值
      searchVal // 需要匹配的值
    itemVal = item.hasOwnProperty(key) ? item[key].toLowerCase() : ''
    searchVal = String(searchParams[key].toLowerCase())

    if (searchList !== undefined && isSelect(searchList, key)) {
      return itemVal === searchVal
    } else {
      return itemVal.includes(searchVal)
    }
  })
}

/**
 * @author liubaohui
 * @desc 判断是否为下拉框做全匹配
 * @param {array} searchList  搜索组件搜索项
 * @param {string} key 查询参数对象的key
 * @returns {*|boolean}
 */
function isSelect(searchList, key) {
  if (Object.prototype.toString.call(searchList) === '[object Array]') {
    return searchList.some(val => val.name === key && val.type === 'select')
  }
}
